import audio from '@ohos.multimedia.audio';
import media from '@ohos.multimedia.media';
let renderModel: audio.AudioRenderer | undefined = undefined;
import { BusinessError } from '@ohos.base';
import fs, { ReadOptions }  from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import buffer from '@ohos.buffer';
class Options {
  offset?: number;
  length?: number;
}

let bufferSize: number = 0;
let avPlayer: media.AVPlayer

let audioStreamInfo: audio.AudioStreamInfo = {
  samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, // 采样率
  channels: audio.AudioChannel.CHANNEL_1, // 通道
  sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // 采样格式
  encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // 编码格式
}
let audioRendererInfo: audio.AudioRendererInfo = {
  usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // 音频流使用类型
  rendererFlags: 0 // 音频渲染器标志
}
let audioRendererOptions: audio.AudioRendererOptions = {
  streamInfo: audioStreamInfo,
  rendererInfo: audioRendererInfo
}

export class AudioPlayback {
  audioPath = ''
  private count: number = 0;
  private isSeek: boolean = true; // 用于区分模式是否支持seek操作
  private fileSize: number = -1;
  private fd: number = 0;

  constructor(audioPath) {
    this.audioPath = audioPath
    // this.init()
    this.avPlayerLive()
  }
  // 初始化，创建实例，设置监听事件
  init() {
    audio.createAudioRenderer(audioRendererOptions, (err, renderer) => { // 创建AudioRenderer实例
      if (!err) {
        // console.info(`${TAG}: creating AudioRenderer success`);
        renderModel = renderer;
        if (renderModel !== undefined) {
          (renderModel as audio.AudioRenderer).on('writeData', (buffer: ArrayBuffer) => {
            this.writeDataCallback(buffer)
          });
          (renderModel as audio.AudioRenderer).on('stateChange', (state: audio.AudioState) => {
            console.info('audio renderer state is: STATE_PREPARED', state);
          });
        }
      } else {
        // console.info(`${TAG}: creating AudioRenderer failed, error: ${err.message}`);
      }
    });
  }

  writeDataCallback (buffer: ArrayBuffer) {
    //确保该路径下存在该资源
    let file: fs.File = fs.openSync(this.audioPath, fs.OpenMode.READ_ONLY);
    let options: Options = {
      offset: bufferSize,
      length: buffer.byteLength
    }
    fs.readSync(file.fd, buffer, options);
    bufferSize += buffer.byteLength;
  }

  // 暂停渲染
  pause() {
    if (renderModel !== undefined) {
      // 只有渲染器状态为running的时候才能暂停
      if ((renderModel as audio.AudioRenderer).state.valueOf() !== audio.AudioState.STATE_RUNNING) {
        console.info('Renderer is not running');
        return;
      }
      // 暂停渲染
      (renderModel as audio.AudioRenderer).pause((err: BusinessError) => {
        if (err) {
          console.error('Renderer pause failed.');
        } else {
          console.info('Renderer pause success.');
        }
      });
    }
  }
  // 停止渲染
  stop() {
    if (renderModel !== undefined) {
      // 只有渲染器状态为running或paused的时候才可以停止
      if ((renderModel as audio.AudioRenderer).state.valueOf() !== audio.AudioState.STATE_RUNNING && (renderModel as audio.AudioRenderer).state.valueOf() !== audio.AudioState.STATE_PAUSED) {
        console.info('Renderer is not running or paused.');
        return;
      }
      // 停止渲染
      (renderModel as audio.AudioRenderer).stop((err: BusinessError) => {
        if (err) {
          console.error('Renderer stop failed.');
        } else {
          console.info('Renderer stop success.');
        }
      });
    }
  }
  // 开始一次音频渲染
  async start() {
    let fdPath = 'fd://';
    let file = await fs.open(this.audioPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    fdPath = fdPath + '' + file.fd;
    // this.isSeek = true; // 支持seek操作
    avPlayer.url = fdPath;
    // if (renderModel !== undefined) {
    //   let stateGroup = [audio.AudioState.STATE_PREPARED, audio.AudioState.STATE_PAUSED, audio.AudioState.STATE_STOPPED];
    //   if (stateGroup.indexOf((renderModel as audio.AudioRenderer).state.valueOf()) === -1) { // 当且仅当状态为prepared、paused和stopped之一时才能启动渲染
    //     // console.error(TAG + 'start failed');
    //     return;
    //   }
    //   // 启动渲染
    //   (renderModel as audio.AudioRenderer).start((err: BusinessError) => {
    //     if (err) {
    //       console.error('Renderer start failed.');
    //     } else {
    //       (renderModel as audio.AudioRenderer).setVolume(1).then(() => {  // 音量范围为[0.0-1.0]
    //         console.info('Invoke setVolume succeeded.');
    //       }).catch((err: BusinessError) => {
    //         console.error(`Invoke setVolume failed, code is ${err.code}, message is ${err.message}`);
    //       });
    //       console.info('Renderer start success.');
    //     }
    //   });
    // }
  }
  // 销毁实例，释放资源
  release() {
    if (renderModel !== undefined) {
      // 渲染器状态不是released状态，才能release
      if (renderModel.state.valueOf() === audio.AudioState.STATE_RELEASED) {
        console.info('Renderer already released');
        return;
      }
      // 释放资源
      (renderModel as audio.AudioRenderer).release((err: BusinessError) => {
        if (err) {
          console.error('Renderer release failed.');
        } else {
          console.info('Renderer release success.');
        }
      });
    }
  }

  // 注册avplayer回调函数
  setAVPlayerCallback(avPlayer: media.AVPlayer) {
    // seek操作结果回调函数
    avPlayer.on('seekDone', (seekDoneTime: number) => {
      console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`);
    })
    // error回调监听函数,当avPlayer在操作过程中出现错误时调用 reset接口触发重置流程
    avPlayer.on('error', (err: BusinessError) => {
      console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`);
      avPlayer.reset(); // 调用reset重置资源，触发idle状态
      avPlayer.url = ''
    })
    // 状态机变化回调函数
    avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => {
      switch (state) {
        case 'idle': // 成功调用reset接口后触发该状态机上报
          console.info('AVPlayer state idle called.');
          avPlayer.release(); // 调用release接口销毁实例对象
          break;
        case 'initialized': // avplayer 设置播放源后触发该状态上报
          console.info('AVPlayer state initialized called.');
          avPlayer.prepare();
          break;
        case 'prepared': // prepare调用成功后上报该状态机
          console.info('AVPlayer state prepared called.');
          avPlayer.play(); // 调用播放接口开始播放
          break;
        case 'playing': // play成功调用后触发该状态机上报
          console.info('AVPlayer state playing called.');
          if (this.count !== 0) {
            // if (this.isSeek) {
            //   console.info('AVPlayer start to seek.');
            //   avPlayer.seek(avPlayer.duration); //seek到音频末尾
            // } else {
            //   // 当播放模式不支持seek操作时继续播放到结尾
            //   console.info('AVPlayer wait to play end.');
            // }
          } else {
            avPlayer.pause(); // 调用暂停接口暂停播放
          }
          this.count++;
          break;
        case 'paused': // pause成功调用后触发该状态机上报
          console.info('AVPlayer state paused called.');
          avPlayer.play(); // 再次播放接口开始播放
          break;
        case 'completed': // 播放结束后触发该状态机上报
          console.info('AVPlayer state completed called.');
          avPlayer.stop(); //调用播放结束接口
          break;
        case 'stopped': // stop接口成功调用后触发该状态机上报
          console.info('AVPlayer state stopped called.');
          avPlayer.reset(); // 调用reset接口初始化avplayer状态
          break;
        case 'released':
          console.info('AVPlayer state released called.');
          break;
        default:
          console.info('AVPlayer state unknown called.');
          break;
      }
    })
  }

  // 以下demo为通过url设置网络地址来实现播放直播码流的demo
  async avPlayerLive() {
    // 创建avPlayer实例对象
    avPlayer = await media.createAVPlayer();
    // 创建状态机变化回调函数
    this.setAVPlayerCallback(avPlayer);
  }
}